package com.example.mybatis.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatis.Pojo.Course;
import com.example.mybatis.Service.CourseService;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CrossOrigin(origins = "http://localhost:8081")
@RestController
public class CourseController {

    @Autowired
    private CourseService courseService;

    //获取课表信息接口
    @RequestMapping("/course")
    public String examdata(@RequestBody Map<String, String> data) throws InterruptedException {
        String username = data.get("username");
        String password = data.get("password");
        //删除原有数据byusernam
        courseService.remove(new QueryWrapper<Course>().eq("username", username));
        //加载驱动
        System.setProperty("webdriver.chrome.driver", "D:\\a\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        //解决打开chrome浏览器data;,异常
        chromeOptions.addArguments("--remote-allow-origins=*");
        // 打开chrome浏览器
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().window().maximize();
        // 进入石河子大学教务系统登录网址
        driver.get("http://authserver.shzu.edu.cn/authserver/login?service=https%3A%2F%2Fjwgl.shzu.edu.cn%2Fsso.jsp");
        Thread.sleep(1000);
        //输入学号，密码
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.tagName("button")).click();
        Thread.sleep(1000);
        //进入课表
        driver.get("https://jwgl.shzu.edu.cn/jsxsd/xskb/xskb_list.do");
        List<WebElement> elements = driver.findElements(By.cssSelector("table#timetable>tbody>tr"));

        for (int i = 0; i < elements.size()-1; i++) {
            List<WebElement> td = elements.get(i).findElements(By.cssSelector("td"));
            for (int j = 0; j < td.size(); j++) {
                List<WebElement> elements1 = td.get(j).findElements(By.cssSelector("td>div.kbcontent"));
                for (int k = 0; k < elements1.size(); k++) {
                    WebElement webElement = elements1.get(k);
                    if(!webElement.getText().trim().equals("")){
                        try{
                            Course course = new Course();

                            int z = 1 ;

                            course.setUsername(username);

                            WebElement element = elements1.get(k).findElement(By.cssSelector("font[onmouseover='kbtc(this)']"));
                            course.setName(element.getText().replace("\n",""));

                            WebElement teacher = elements1.get(k).findElement(By.cssSelector("font[title=教师]"));
                            course.setLaoshi(teacher.getText());

                            //星期
                            String week = "";
                            switch (j+1) {
                                case 1:
                                    week = "一";
                                    break;
                                case 2:
                                    week = "二";
                                    break;
                                case 3:
                                    week = "三";
                                    break;
                                case 4:
                                    week = "四";
                                    break;
                                case 5:
                                    week = "五";
                                    break;
                                case 6:
                                    week = "六";
                                    break;
                                case 7:
                                    week = "日";
                                    break;
                            }
                            course.setWeek(week);

                            WebElement room = elements1.get(k).findElement(By.cssSelector("font[title=教室]"));
                            course.setJiaoshi(room.getText());

                            List<WebElement> zc = elements1.get(k).findElements(By.cssSelector("font[title='周次(节次)']"));
                            String data1 = zc.get(k).getText();
                            Pattern pattern = Pattern.compile("(?<=\\[)[^\\节]+");
                            Matcher matcher = pattern.matcher(data1);
                            while (matcher.find()) {
                                String group = matcher.group();
                                String[] split = group.split("-");
                                int i1 = Integer.parseInt(split[0]);
                                int i2 = Integer.parseInt(split[1]);
                                course.setCourseLength(i2 - i1 + 1);
                                course.setCourseIndex(i1 - 1);
                            }

                            while(z<=zc.size()){
                                String weekTime = zc.get(z-1).getText();
                                Pattern pattern1 = Pattern.compile("(.*?)[^\\(]+");
                                Matcher matcher1 = pattern1.matcher(weekTime);
                                while (matcher1.find()) {
                                    String group1 = matcher1.group();
                                    System.out.println(group1);
                                    String[] weekIndexes = group1.split(",");
                                    for (String weekIndex : weekIndexes) {
                                        if (weekIndex.contains("-")) { // 如果包含连字符，说明是一个范围
                                            String[] range = weekIndex.split("-");
                                            int start = Integer.parseInt(range[0]);
                                            int end = Integer.parseInt(range[1]);
                                            for (int m = start; m <= end; m++) {
                                                course.setWeekIndex(String.valueOf(m));
                                                System.out.println(course);
                                                //存储if里获取的course
                                                courseService.save(course);
                                            }
                                        } else { // 否则直接设置
                                            course.setWeekIndex(weekIndex.trim());
                                            System.out.println(course);
                                            //存储if里获取的course
                                            courseService.save(course);
                                        }
                                    }
                                    break;
                                }
                                z++;
                            }
                        }catch (Exception e){
                            continue;
                        }
                    }

                }

            }
        }
        return "success";
    }

    //前端课表接口
    @RequestMapping("/test12351/{username}")
    public List<Course> listALL(String weekIndex,@PathVariable String username){
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        courseLambdaQueryWrapper.eq(Course::getUsername, username);
        courseLambdaQueryWrapper.eq(Course::getWeekIndex,weekIndex);
        List<Course> list = courseService.list(courseLambdaQueryWrapper);
        return list;
    }

}